//
//  PhotoAppHome.swift
//  SwiftUILean
//
//  Created by wyknmjj on 2024/5/13.
//

import SwiftUI

struct PhotoAppHome: View {
    @Environment(PhotoCoordinator.self) private var coordinator
    var body: some View {
        if coordinator.isLoading {
            Text("Loading...")
        }else{
            switch coordinator.result{
            case .error(let e):
                Text("Error: \(e)")
            case .success(data: let items):
                ScrollViewReader{reader in
                    ScrollView(.vertical){
                        LazyVStack(alignment:.leading, spacing: 0){
                            Text("Recents")
                                .font(.largeTitle.bold())
                                .padding(.top,20)
                                .padding(.horizontal,15)
                            LazyVGrid(columns: Array(repeating:GridItem(spacing:3),count: 3),spacing: 3){
                                ForEach(items) { item in
                                    GridImageView(item)
                                        .id(item.id)
                                        .didFrameChange{ frame, bounds in
                                            let minY = frame.minY
                                            let maxY = frame.maxY
                                            let height = bounds.height
                                            
                                            if maxY < 0 || minY > height {
                                                coordinator.toggleVisible(id: item.id, show: false)
//                                                item.appeared = false
                                            }else{
                                                coordinator.toggleVisible(id: item.id, show: true)
//                                                item.appeared = true
                                            }
                                        }
                                        .onDisappear{
                                                coordinator.toggleVisible(id: item.id, show: false)
//                                            item.appeared = false
                                        }
                                        .onTapGesture {
                                            coordinator.selectedItem = item
                                        }
                                }
                            }.padding(.vertical,10)
                        }
                    }.onChange(of: coordinator.selectedItem) { oldValue, newValue in
                        if let id=newValue?.id,!coordinator.itemVisible(id: id){
                            reader.scrollTo(id,anchor: .bottom)
                        }
                    }
                }.toolbar(.hidden, for: .navigationBar)
            }
        }
    }
    
    @ViewBuilder
    func GridImageView(_ item:PhotoItem)->some View{
        GeometryReader{
            let size = $0.size
            
            
            Rectangle().fill(.clear)
                .anchorPreference(
                    key: PhotoHeroKey.self,
                    value: .bounds,
                    transform: { anchor in
                    return [item.id+"SOURCE":anchor]
                })
            
            
            if let previewImage=item.previewImage{
                Image(uiImage: previewImage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: size.width,height: size.height,alignment: .center)
                    .clipped()
                    .opacity(coordinator.selectedItem?.id==item.id ? 0 : 1)
            }
        }
        .frame(height: 130)
        .contentShape(.rect)
    }
}

#Preview {
    PhotoAppView()
//    PhotoAppHome()
}
